package image;

import java.io.File;
import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * This servlet is used for the possibility of deleting directory recursively
 * and for deleting single files.
 * 
 * @author cuche
 *
 */
public class FileDeleterServlet extends HttpServlet {
	private static final String FILE_TO_DELETE_PARAM = "fileToDelete";
	private static final String URL_TO_FOLDER_LIST = "/folders";
	private static final long serialVersionUID = 1L;
       

    public FileDeleterServlet() {
        super();
    }


	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}


	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String fileToDeletePath = request.getParameter(FILE_TO_DELETE_PARAM);
		File fileToDelete = new File(fileToDeletePath);
		String pathToParrent = fileToDelete.getParentFile().getPath();
		delete(fileToDelete);
		
		ServletContext context = getServletContext();
		String urlToCurrentFolder = String.format("%s?dirPath=%s", URL_TO_FOLDER_LIST, pathToParrent);
		RequestDispatcher rd = context.getRequestDispatcher(urlToCurrentFolder);
		rd.forward(request, response);
	}
	
	/**
	 * This method is responsible for deleting files.
	 * If it's a directory it deletes everything inside of it
	 * and the directory itself. If its only an image file
	 * it deletes it aswell.
	 * 
	 * @param fileToDelete
	 */
	 public static void delete(File fileToDelete) {
		 if (fileToDelete.isDirectory()) {
	    		if (fileToDelete.list().length==0) { 
	    			fileToDelete.delete();
	 
	    		} else {

	        	   String files[] = fileToDelete.list();	 
	        	   for (String temp : files) {
	        	      File fileDelete = new File(fileToDelete, temp);
	        	      delete(fileDelete);
	        	   }
	        	   if (fileToDelete.list().length==0) {
	        		   fileToDelete.delete();
	        	   }
	    		}
	 
	    	} else {
	    		fileToDelete.delete();
	    	}
	 }

}
